package com.geeksaga.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.geeksaga.common.util.CacheUtil;
import com.geeksaga.dao.ProjectDao;
import com.geeksaga.domain.Project;

/**
 * @author newbie
 * @since 0.1
 */
@Service
public class ProjectServiceImpl implements ProjectService {

    protected static final Log logger = LogFactory.getLog(ProjectServiceImpl.class);
    
    @Autowired protected ProjectDao projectDao;
    
    /* (non-Javadoc)
     * @see com.geeksaga.service.ProjectService#loadCache()
     */
    public void loadCache() throws DataAccessException {
        List<Project> list = projectDao.list();
        
        Map<String, Project> cacheMap = new HashMap<String, Project>();
        
        for(Project project : list) {
//            FIXME set manager
//            project.setManager(bbsManagerDao.findByBbsType(project));
            
            cacheMap.put(project.getProjectCode(), project);
        }

        if(!cacheMap.isEmpty())
            CacheUtil.put(CacheUtil.CACHE, CacheUtil.KEY_PROJECT, cacheMap);
    }
    
    /* (non-Javadoc)
     * @see com.geeksaga.service.ProjectService#findCacheByProjectCode(java.lang.String)
     */
    public Project findCacheByProjectCode(String projectCode) {
        Map<String, Project> cacheMap = CacheUtil.get(CacheUtil.CACHE, CacheUtil.KEY_PROJECT);
        
        if(cacheMap == null) {
            loadCache();
            
            cacheMap = CacheUtil.get(CacheUtil.CACHE, CacheUtil.KEY_PROJECT);
        }
        
        return (cacheMap != null) ? cacheMap.get(projectCode) : null;
    }
    
    /* (non-Javadoc)
     * @see com.geeksaga.service.ProjectService#add(com.geeksaga.domain.Project)
     */
    public Project add(Project project) throws DataAccessException {
        return projectDao.add(project);
    }

    /* (non-Javadoc)
     * @see com.geeksaga.service.ProjectService#list()
     */
    public List<Project> list() throws DataAccessException {
        return projectDao.list();
    }
}